//
//  gwchaxunViewController.m
//  tongxiangOASystem
//
//  Created by michael on 17/4/11.
//  Copyright © 2017年 czd. All rights reserved.
#import "gwcxxqViewController.h"
#import "FBMCombox.h"
#import "LGLSearchBar.h"
#import "ckUnDonelistCell.h"
#import "gwchaxunViewController.h"
#import "SQMenuShowView.h"
#import "daibanTableViewCell.h"

#define KShowYearsCount 30
@interface gwchaxunViewController ()<FBMComboxDelegate>

@property (nonatomic, strong) NSArray *yearArray;
@property (nonatomic, strong) NSArray *typeArray;

@property (nonatomic, assign) NSInteger year;

@property (strong, nonatomic)  SQMenuShowView *showView;
@property (assign, nonatomic)  BOOL  isShow;
@property (strong, nonatomic)  SQMenuShowView *showView2;
@property (assign, nonatomic)  BOOL  isShow2;
@property(nonatomic,strong)NSMutableArray * dataArray;
@property(nonatomic,assign)NSInteger totalCounts; //总条数
@property(nonatomic,assign)NSInteger currentPage; //当前页
@property(nonatomic,assign)BOOL isSearching;
@property(nonatomic,strong)NSString * searchyear;

@property(nonatomic,strong)NSString * searchtype;

@property(nonatomic,strong)NSString * searchText;
@property (nonatomic, strong) HWOptionButton *yearBtn;
@property (nonatomic, strong) HWOptionButton *yearBtn2;
@property(nonatomic,strong)NSDictionary * adic;

@end

@implementation gwchaxunViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"办毕文件";

     NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute fromDate:[NSDate date]];
    _year = [components year];
 NSInteger firstYear = 2004;
    NSMutableArray *yearArray = [NSMutableArray array];
    for (int i = 0; i <= _year-2004; i++) {
        [yearArray addObject:[NSString stringWithFormat:@"%ld", _year - i]];
    }
    _yearArray = yearArray;
    _typeArray = @[@"全部文件",@"本人经办"];
            self.automaticallyAdjustsScrollViewInsets = NO;

    self.view.backgroundColor = [UIColor whiteColor];
              UIColor *myColor = [UIColor colorWithWhite:0.5 alpha:0.2];
              _bgview = [[UIView alloc]initWithFrame:self.view.frame];
              _bgview.backgroundColor = myColor;
//              [self.view addSubview:_bgview];
              [self _iniview];
                 __weak typeof(self) weakSelf = self;

              [self.tableView addHeaderWithCallback:^{
        weakSelf.currentPage = 1;
 if (weakSelf.isSearching) {
    [weakSelf loadSearchData:_searchText];
}
    else    {
        [weakSelf loadData]; //加载网络数据
             }
    }];
    [self.tableView headerBeginRefreshing];
    
    [self.tableView addFooterWithCallback:^{
        if ((self.currentPage - 1)*KPageSize < self.totalCounts ){
        if (weakSelf.isSearching) {
    [weakSelf loadsearchMore];
}
    else    {
             [weakSelf loadMore];
             }
        }else{
        
            [weakSelf.tableView footerEndRefreshing];
            [weakSelf.view makeToast:@"没有更多了"];
    
        }
       
    }];
    
  UIBarButtonItem * rightIem = [[UIBarButtonItem alloc] initWithTitle:@"搜索" style:UIBarButtonItemStylePlain target:self action:@selector(searchAction)];
        self.navigationItem.rightBarButtonItem = rightIem;


    // Do any additional setup after loading the view.
}
#pragma mark 搜素
-(void)searchAction{
    
    [UIAlertView showWithTitle:@"搜索" message:nil style:UIAlertViewStylePlainTextInput cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
        [self.view endEditing:YES];
        
        if (buttonIndex == 1) {
            UITextField * textField = [alertView textFieldAtIndex:0];
            if (textField.text.length !=0) {
                 [self.view endEditing:YES];
//         self.isSearching = YES;

 gwcxxqViewController*vc = [[gwcxxqViewController alloc]init];
vc.searchText =textField.text;
vc.searchyear =_searchyear;
[self.navigationController pushViewController:vc animated:YES];
//        _searchText = textField.text;
//    [self loadSearchData:_searchText];
//
//                [self.dataArray removeAllObjects];
//                self.isSearching = YES;
//                self.currentPage = 1;
//                [self loadSearchData:textField.text];
            }
            
        }
        
    }];
    
}
- (void)_iniview{
//float width = (kScreenWidth-30);
//_label1 = [[UILabel alloc]initWithFrame:CGRectMake(10,10, width-40, 30)];
// _label1.backgroundColor = [UIColor whiteColor];
//    _label1.text = [NSString stringWithFormat:@"%ld",
//                    (long)_year];
//
//
////[self.bgview addSubview:_label1];
//
//  //搜索框
////     LGLSearchBar * searchBar = [[LGLSearchBar alloc] initWithFrame:CGRectMake(10,10+30, kScreenWidth-20 , 40) searchBarStyle:LGLSearchBarStyleDefault];
//          LGLSearchBar * searchBar = [[LGLSearchBar alloc] initWithFrame:CGRectMake(10,0, kScreenWidth-20 , 40) searchBarStyle:LGLSearchBarStyleDefault];
//
//     UIColor *textColor = self.view.tintColor;
//     searchBar.tintColor = textColor;
//
//    searchBar.barBackgroudColor = textColor;
//                  UIColor *myColor = [UIColor colorWithWhite:0.5 alpha:0.2];
////     searchBar.textBordStyle = LGLTextBorderStyleNoine;
//
//  [searchBar setSearchBarBordeWidth:2 bordColor:textColor bordRadius:5];
//    [searchBar searchBarTextSearchTextBlock:^(NSString *searchText) {
//        NSLog(@"%@", searchText);
//        if (!searchText) {
//    [self.bgview makeToast:@"请输入关键字"];
//}
//        [self.view endEditing:YES];
//         self.isSearching = YES;
//        _searchText = searchText;
//    [self loadSearchData:_searchText];
//
//
//    }];
//    [self.bgview addSubview:searchBar];
//
//
//       //年份按钮
//    _yearBtn = [[HWOptionButton alloc] initWithFrame:CGRectMake(_label1.right, _label1.top, 40, 30)];
//    _yearBtn.array = _yearArray;
//    _yearBtn.title = [NSString stringWithFormat:@"%ld",
//                    (long)_year];
//
//    _yearBtn.row = KShowYearsCount / 2;
//    _yearBtn.delegate = self;
//    [self.bgview addSubview:_yearBtn];
    
   _button1 = [[UIButton alloc] initWithFrame:CGRectMake(10, 5, (kScreenWidth-30)/2, 30)];
    [_button1 setTitle:[NSString stringWithFormat:@"%ld",(long)_year] forState:UIControlStateNormal];
_searchyear =[NSString stringWithFormat:@"%ld",(long)_year];
//   _button1.backgroundColor = [UIColor redColor];
   [_button1 addTarget:self action:@selector(buttonAction1) forControlEvents:UIControlEventTouchUpInside];
          [_button1.layer setBorderColor:[UIColor blackColor].CGColor];
    [_button1.layer setBorderWidth:1];
 [_button1.layer setMasksToBounds:YES];
   [_button1 setTitleColor:[UIColor blackColor]forState:UIControlStateNormal];
        _button1.layer.cornerRadius = _button1.height/2;
//[_button1 setImage:[UIImage imageNamed:@"下拉@2x"] forState:UIControlStateNormal];
[_button1 layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight
                        imageTitleSpace:10];
//    _button1.layer.shadowOffset = CGSizeMake(1,1);
//    _button1.layer.shadowOpacity = 0.3;
//    _button1.layer.shadowColor = [UIColor blackColor].CGColor;
    [self.view addSubview:_button1];

_button2 = [[UIButton alloc] initWithFrame:CGRectMake(_button1.right+10, 5, (kScreenWidth-30)/2, 30)];
       [_button2 setTitle:@"全部文件" forState:UIControlStateNormal];
_searchtype = @"all";
              _searchText =@"";

      [_button2.layer setBorderColor:[UIColor blackColor].CGColor];
    [_button2.layer setBorderWidth:1];
 [_button2.layer setMasksToBounds:YES];
   [_button2 setTitleColor:[UIColor blackColor]forState:UIControlStateNormal];
   [_button2 addTarget:self action:@selector(buttonAction2) forControlEvents:UIControlEventTouchUpInside];
        _button2.layer.cornerRadius = _button2.height/2;
//    _button2.layer.shadowOffset = CGSizeMake(1,1);
//    _button2.layer.shadowOpacity = 1;
//    _button2.layer.shadowColor = [UIColor blackColor].CGColor;
//   _button2.backgroundColor = [UIColor redColor];
    [self.view addSubview:_button2];
    
 _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 40, kScreenWidth, kScreenHeight-kTopHeight-30-10) style:UITableViewStylePlain];
        self.tableView.backgroundColor = [UIColor colorWithHexString:@"efeff4"];

         self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    _tableView.dataSource = self;
    _tableView.delegate = self;
    
    
    [self.view addSubview:_tableView];
    
//     FBMCombox *combox = [[FBMCombox alloc] initWithItems:_yearArray withFrame:CGRectMake(10,64+10, width-40, 30)];
//    combox.delegate = self;
////    [self.bgview addSubview:combox];
//
//   _showView = [[SQMenuShowView alloc]initWithFrame:CGRectMake(_label1.left, _label1.bottom, 100, 200)  items:_yearArray showPoint:CGPointMake(_label1.left+25, _label1.bottom)];
//    _showView.sq_backGroundColor = [UIColor whiteColor];
//    [self.bgview addSubview:_showView];
//  __weak typeof(self) weakSelf = self;
//    [self.showView selectBlock:^(SQMenuShowView *view, NSInteger index) {
//        weakSelf.isShow = YES;
//        _label1.text = [NSString stringWithFormat:@"点击第%ld个item",index+1];
//        NSLog(@"点击第%ld个item",index+1);
//    }];
//
//    _label2 = [[UILabel alloc]initWithFrame:CGRectMake(_button1.right+10,64+10, width-40, 30)];
// _label2.backgroundColor = [UIColor whiteColor];
//
////[self.bgview addSubview:_label2];
//   //年份按钮
//    _yearBtn2 = [[HWOptionButton alloc] initWithFrame:CGRectMake(_label2.right, _label1.top, 40, 30)];
//    _yearBtn2.array = @[@"item1",@"item2",@"item3",@"item4",@"item5",@"item5",@"item5",@"item5",@"item5",@"item5"];
//
//    _yearBtn2.row = @[@"item1",@"item2",@"item3",@"item4",@"item5",@"item5",@"item5",@"item5",@"item5",@"item5"].count / 2;
//    _yearBtn2.delegate = self;
////    [self.bgview addSubview:_yearBtn2];
//
//
//_button2 = [UIButton buttonWithType:UIButtonTypeCustom];
//_button2.frame = CGRectMake(_label2.right, _label1.top, 40, 30);
// _button2.backgroundColor = [UIColor whiteColor];
//[_button2 setBackgroundImage:[UIImage imageNamed:@"下箭头"] forState:UIControlStateNormal];
// [_button2 addTarget:self action:@selector(buttonAction2)forControlEvents:UIControlEventTouchUpInside];
////[self.bgview addSubview:_button2];
//
//   _showView2 = [[SQMenuShowView alloc]initWithFrame:CGRectMake(_label2.left, _label2.bottom, 100, 0)  items:@[@"item1",@"item2",@"item3",@"item4",@"item5",@"item5",@"item5",@"item5",@"item5",@"item5"]showPoint:CGPointMake(_label2.left+25, _label2.bottom)];
//    _showView2.sq_backGroundColor = [UIColor whiteColor];
//    [self.bgview addSubview:_showView2];
//    [self.showView2 selectBlock:^(SQMenuShowView *view, NSInteger index) {
//        weakSelf.isShow2 = NO;
//        _label2.text = [NSString stringWithFormat:@"点击第%ld个item",index+1];
//        NSLog(@"点击第%ld个item",index+1);
//    }];
//
//
   

    
    
}
-(void)loadSearchData:(NSString*)Searchtext{
//
    __weak typeof(self) weakSelf = self;
        NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
_currentPage = 1;
    NSArray * array = @[@{@"condition":_searchText},@{@"dbpath": _searchyear},@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
NSLog(@"%@",array);
 [HttpTools requestWithURL:KexexchSearchURL arrays:array method:@"ArchiveYearSearch" success:^(id JSON) {
  if (self.currentPage ==1) {
            [self.dataArray removeAllObjects];
        }
        _adic= JSON[@"display"];

      _dataArray =   [NSMutableArray array];
        NSArray *array = JSON[@"data"];
  self.totalCounts =[JSON[@"number"] intValue];

if(JSON[@"number"]){

       self.title = [NSString stringWithFormat:@"办毕文件(%@)",JSON[@"number"] ];}

       else{

       self.title = @"办毕文件";
       }         for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}
if (self.dataArray.count ==0) {
            [self.view makeToast:@"暂时还没数据哦"];
        }
        [weakSelf.tableView footerEndRefreshing];
        [weakSelf.tableView reloadData];
        weakSelf.currentPage++;
     
        if (self.tableView.headerRefreshing) {
            [self.tableView headerEndRefreshing];
        }
        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
     
    } failure:^(NSError *error) {
        if (self.tableView.headerRefreshing) {
            [self.tableView headerEndRefreshing];
        }
        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
    }];
    




}
- (void)loadsearchMore{
    __weak typeof(self) weakSelf = self;
        NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];

    NSArray * array = @[@{@"condition":_searchText},@{@"dbpath": _searchyear},@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];

 [HttpTools requestWithURL:KexexchSearchURL arrays:array method:@"ArchiveYearSearch" success:^(id JSON) {
                NSArray *array = JSON[@"data"];

 for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}
_adic= JSON[@"display"];
//        self.totalCounts =[JSON[@"number"] intValue];
//
//       self.title = [NSString stringWithFormat:@"公文查询(%@)",JSON[@"number"] ];
    self.currentPage++;
        [self.tableView footerEndRefreshing];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        if (self.tableView.headerRefreshing) {
            [self.tableView headerEndRefreshing];
        }
        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
    }];
    




}
- (void)didSelectOptionInHWOptionButton:(HWOptionButton *)optionButton
{
if ((optionButton = _yearBtn)) {

    _label1.text = optionButton.title;


}if ((optionButton = _yearBtn2)) {
    _label2.text = optionButton.title;

}
   }

#pragma mark 加载网络数据
-(void)loadData{
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"year":_searchyear},@{@"type":_searchtype},@{@"sName":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    [HttpTools requestWithURL:KexexcharchiveURL arrays:array method:@"archivePage"success:^(id JSON) {
    NSLog(@"%@",JSON);
        if (self.currentPage ==1) {
            [self.dataArray removeAllObjects];
        }
      _dataArray =   [NSMutableArray array];
        NSArray *array = JSON[@"data"];
         self.totalCounts =10000;

//       self.title = [NSString stringWithFormat:@"公文查询(%@)",JSON[@"number"] ];

         for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}
_adic= JSON[@"display"];

        [self.tableView reloadData];
        [self.tableView headerEndRefreshing];
        self.currentPage++;
        if (self.dataArray.count ==0) {
            [self.view makeToast:@"暂时还没数据哦"];
        }
    } failure:^(NSError *error) {
        [self.tableView headerEndRefreshing];
    }];
    
}

#pragma mark 加载更多
-(void)loadMore{
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
//        NSArray * array = @[@{@"userId":userId},@{@"dbpath":[NSString stringWithFormat:@"%ld",_year]},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];

    NSArray * array = @[@{@"year":_searchyear},@{@"tyoe":_searchtype},@{@"sName":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    [HttpTools requestWithURL:KexexcharchiveURL arrays:array method:@"archivePage" success:^(id JSON) {
                NSArray *array = JSON[@"data"];

 for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}
//_adic= JSON[@"display"];

//       self.title = [NSString stringWithFormat:@"公文查询(%lu)",(unsigned long)[array count]];
    self.currentPage++;
        [self.tableView footerEndRefreshing];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [self.tableView footerEndRefreshing];
    }];
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    UnDoneModel * model = self.dataArray[indexPath.row];
//    CGFloat height = 0;
//    CGFloat  titlesize  = [OAToolBox sizebyText:model.title font:14 minsWidth:80];
//
//    NSString * desstring = [NSString stringWithFormat:@"%@",model.time];
//    CGFloat dessize = [OAToolBox sizebyText:desstring font:13 minsWidth:40];;
//    height = titlesize + dessize + 20;
//    return  height;
    NSDictionary *dic = self.dataArray[indexPath.row];

    CGFloat  titleFloat  = [OAToolBox sizebyText:dic[@"subject"] font:14 minsWidth:60];

    return  titleFloat  +10+10+20;
}




#pragma mark UITableView dataScource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
 static NSString *CellIdentifier = @"Cell";

    daibanTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
  if (cell==nil) {
        cell=[[daibanTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
 NSDictionary *dic = self.dataArray[indexPath.row];
    cell.dic = dic;
    cell.adic = _adic;
    cell.number = [NSString stringWithFormat:@"%ld",(long)indexPath.row+1];
    return cell;




//    OAUnDoneListCell * cell = [OAUnDoneListCell cellWithTableView:tableView];
//    UnDoneModel * model = self.dataArray[indexPath.row];
//    cell.model = model;
//    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

      UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
        NSDictionary *dic = self.dataArray[indexPath.row];

     UnDoneModel * model = self.dataArray[indexPath.row];
     detailViewController * detailVC = (detailViewController *)[storyBoard instantiateViewControllerWithIdentifier:@"detail"];
detailVC.fileId = dic[@"unid"];
detailVC.type = @"chaxun";
detailVC.year =  _searchyear;

[self.navigationController pushViewController:detailVC animated:YES];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (void)buttonAction1{

 PickerChoiceView *picker = [[PickerChoiceView alloc]initWithFrame:self.view.bounds];

    picker.delegate = self;
    picker.type = @"year";
        picker.selectLb.text = @"年份选择";
        picker.customArr = _yearArray;


    [self.view addSubview:picker];



 }
 - (void)PickerSelectorIndixString:(NSString *)str:(NSString *)type{
 if ([type isEqualToString:@"year"]) {
    
    _searchyear = str;
    [_button1 setTitle:str forState:UIControlStateNormal];
            self.currentPage = 1;

[self loadData];
}else{
_searchtype = str;
if ([str isEqualToString:@"全部文件"]) {
    _searchtype = @"all";
}else{
    _searchtype = @"br";


}
[_button2 setTitle:str forState:UIControlStateNormal];
            self.currentPage = 1;
[self loadData];
}
 
 }
 - (void)buttonAction2{

 PickerChoiceView *picker = [[PickerChoiceView alloc]initWithFrame:self.view.bounds];

    picker.delegate = self;
    picker.type = @"type";
        picker.selectLb.text = @"类型选择";
        picker.customArr = _typeArray;


    [self.view addSubview:picker];


 }
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

